<template>
  <div class="login-box">
    <div class="box-title">贝斯特管理后台</div>
    <div class="box-content">
      <Form ref="formLogin" :model="formLogin" :rules="ruleLogin">
        <Form-item prop="account">
          <i-input type="text" size="large" autofocus v-model="formLogin.account" placeholder="登录账号" @keyup.enter.native="handleSubmit('formLogin')">
            <Icon type="ios-person-outline" slot="prepend"></Icon>
          </i-input>
        </Form-item>
        <Form-item prop="password">
          <i-input type="password" size="large" v-model="formLogin.password" placeholder="登录密码" @keyup.enter.native="handleSubmit('formLogin')">
            <Icon type="ios-locked-outline" slot="prepend"></Icon>
          </i-input>
        </Form-item>
        <Form-item>
          <Button type="primary" size="large" long :loading="btnLoad" @click="handleSubmit('formLogin')">登录</Button>
        </Form-item>
      </Form>
    </div>
  </div>
</template>

<script>
  import { setCookie } from '~/utils/cookie'
  // 页面逻辑
  export default {
    // 页面布局
    layout: 'fullback',
    // 数据绑定
    data () {
      return {
        formLogin: {
          mode: 1
        },
        ruleLogin: {
          account: [
            { required: true, message: '请填写账号', trigger: 'blur' },
            { type: 'string', min: 5, message: '账号不少于5位', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请填写密码', trigger: 'blur' },
            { type: 'string', min: 5, message: '密码不少于5位', trigger: 'blur' }
          ]
        },
        btnLoad: false
      }
    },
    // 页面函数
    methods: {
      // 提交表单
      handleSubmit (name) {
        const app = this
        app.btnLoad = true
        app.$refs[name].validate(valid => {
          if (valid) {
            app.userLogin()
          } else {
            app.btnLoad = false
          }
        })
      },

      // 用户登录
      async userLogin() {
        const app = this
        let { data } = await app.$axios.post('/user/v1/login', app.formLogin)
        if (data.code === 100) {
          setCookie('token', data.result.token, 1)
          app.$Message.success('登录成功,欢迎回来！')
          app.$router.replace('/')
          app.btnLoad = false
        } else {
          app.$Message.error(data.msg)
          app.btnLoad = false
        }
      }
    }
  }
</script>

<style scoped lang="less">
  .login-box {
    position: absolute;
    z-index: 100;
    top: 150px;
    left: 50%;
    width: 400px;
    padding: 45px 50px 30px;
    margin-left: -200px;
    background-color: rgba(255,255,255,.96);
    border-radius: 2px;
    .box-title {
      text-align: center;
      font-size: 20px;
      margin-bottom: 25px;
    }
  }

  @media screen and (max-width: 768px) {
    .login-box {
      top: 30%;
      width: 340px;
      padding: 20px 20px 10px;
      margin-left: -170px;
    }
  }
</style>
